<?php

namespace app\repository;

use app\common\http\WXService;
use app\popo\model\User;


class UserRepository
{
    /**
     * @throws \Exception
     */
    public function findOrCreatByOpendId($code): User
    {
        // 如果没查到，调微信接口拿用户信息
        $wxUserInfo = WXService::login($code);
        if (!$wxUserInfo) {
            throw new \Exception("获取微信用户信息失败");
        }

        // 先查库
        $openId = $wxUserInfo["openid"];
        $user = User::where('openid', $openId)->first();
        if ($user) {
            return $user;
        }

        // 创建用户
        $user = new User();
        $user->openid     = $openId;
        $user->name       = "dwq";
        $user->sex        = 1;
        $user->avatar     =  '';
        $user->create_time = date('Y-m-d H:i:s');

        $user->save();

        return $user;
    }

}